<?php

class wxapi_base_int
{   

    public $postObj = '';
    public $CI = '';

    /**
     * @abstract 初始化函数
     */
    function __construct(){
        $this->CI =& get_instance();
    }
    

    /**
     * @abstract 开发接口配置验证
     */
    public function valid()
    {   
        if(isset($_GET["echostr"])){
            $echoStr = $_GET["echostr"];
            //valid signature , option
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }   
        }
    }
    
    
    /**
     * @abstract 消息路由
     * @since 2014-08-19 13:32:42
     */
    public function responseMsg()
    {
        // debug
        $postStr = $this->debug('prod');

        //extract post data
        if (!empty($postStr)){
            // 解析xml文件
            $this->postObj = array();
            $this->postObjRaw = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            // 只解析单层
            foreach ($this->postObjRaw as $key => $value) {
                $this->postObj[$key] = strval($value);
            }

            // 判断消息类型
            $MsgType = strtolower($this->postObj['MsgType']);

            if($MsgType == 'event'){
                $MsgType = strtolower($this->postObj['Event']);
            }

            switch ($MsgType) {
                case 'text':
                    $this->CI->load->model('weixin/search_model','search');
                    $res = $this->CI->search->com_res($this->postObj['Content'],ihome_id);

                    if(count($res)){
                        $this->responseSearch($res);
                    }

                    break;
                
                case 'location':
                    $contentStr = "Now At：\nLatitude：".$this->postObj['Latitude']."\n";
                    $contentStr = $contentStr."Longitude：".$this->postObj['Longitude'];
                    $this->responseText($contentStr);
                    break;

                case 'subscribe':
                    // $this->CI->load->model('weixin/user_normal_model','wx_user');
                    // $data = array(
                    // 	'openid' => $this->postObj['FromUserName'],
                    // 	'gh_num' => $this->postObj['ToUserName'],
                    //     'subscribe' => 1,
                    // );

                    /**
                     * @abstract  ***（昵称），欢迎您回家
                     * @param   家园通知、便利服务、优享生活、邻里互助……精彩尽在 “指间社区”。点击图片，欢迎回家！
                     * @param http://pd-hz-1.oss-cn-hangzhou.aliyuncs.com/ihome_subscribe.jpg
                     */

                    $api_url = base_url()."system/wx_openid_js/redirect_api/?gh_num=%s&real_gh_num=%s&callback=%s";

                    // 参数整理
                    $PicUrl = s_image."@ihome-mobile-200";
                    
                    $Url = sprintf($api_url,$this->postObj['ToUserName'],$this->postObj['ToUserName'],urlencode(base_url().'user/user_resident/my_steward/'));

                    // $this->CI->wx_user->update_user($data,$this->postObj['FromUserName']);


                    // $this->responseNews('欢迎您回家，我们恭候多时啦','家园通知、便利服务、优享生活、邻里互助……精彩尽在 “指间社区”。点击图片，欢迎回家！',$PicUrl,$Url);

                    $this->responseNews(s_title,s_brief,$PicUrl,$Url);
                    
                    break;

                case 'unsubscribe':
                    // $this->CI->load->model('weixin/user_normal_model','wx_user');
                    // $data = array(
                    //     'openid' => $this->postObj['FromUserName'],
                    //     'gh_num' => $this->postObj['ToUserName'],
                    //     'subscribe' => 0,
                    // );

                    // $this->CI->wx_user->update_user($data,$this->postObj['FromUserName']);

                    break;
                
                case 'click':
                    $api = "http://zhijian.plusman.cn/dashboard/panel_news/crazyAlert/%s/%s/%s";
                    file_get_contents(sprintf($api,$this->postObj['ToUserName'],ihome_id,$this->postObj['FromUserName']));
                    break;

                default:
                    $this->responseText($MsgType);
                    break;
            }

        }else {
            echo "Poil GLOBALS";
            exit;
        }
    }
     
    
    
    /*********************辅助函数*************************************/
    
    /**
     * @abstract 回复文本消息
     * @return xml
     */
    function responseText($contentStr){
        $fromUsername = $this->postObj['FromUserName'];
        $toUsername = $this->postObj['ToUserName'];
        $time = time();

    	$textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";

        $msgType = "text";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        echo $resultStr;
        exit();
    }
    
    
    /**
     * @param string $Title 图文标题
     * @param string $Description 图文描述
     * @param string $PicUrl 图片链接
     * @param string $Url 原文链接
     */
    function responseNews($Title,$Description = '',$PicUrl = '',$Url = ''){
    	$fromUsername = $this->postObj['FromUserName'];
    	$toUsername = $this->postObj['ToUserName'];
    	$time = time();
    	
    	$newsTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>1</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[%s]]></Title> 
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                    </item>
                    </Articles>
                    </xml>";

        $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $Title, $Description,$PicUrl,$Url);
        echo $resultStr;
        exit();
    }



    /**
     * @abstract 回复搜索消息
     */
    function responseSearch($search){
        $fromUsername = $this->postObj['FromUserName'];
        $toUsername = $this->postObj['ToUserName'];
        $time = time();
        
        $items = '';
        foreach ($search as $key => $value) {
            $item = "<item>
                    <Title><![CDATA[%s]]></Title> 
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                    </item>";
            $items .= sprintf($item,$value['title'],$value['title'],$value['img'],$value['link'].'/?token='.TOKEN);
        }
        

        $newsTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>%d</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[搜索结果]]></Title> 
                    <Description><![CDATA[]]></Description>
                    <PicUrl><![CDATA[]]></PicUrl>
                    <Url><![CDATA[]]></Url>
                    </item>
                    %s
                    </Articles>
                    </xml>";

        $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time,count($search)+1,$items);
        echo $resultStr;
        exit();
    }
    
    /**
     * @abstract 签名生成
     * @return boolean
     */
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * @abstract debug 消息类型
     * @param string $type
     * @return xml
     */
    private function debug($type) {
    	switch ($type) {
    		case 'text':
    			return "<xml>
                         <ToUserName><![CDATA[toUser]]></ToUserName>
                         <FromUserName><![CDATA[fromUser]]></FromUserName> 
                         <CreateTime>1348831860</CreateTime>
                         <MsgType><![CDATA[text]]></MsgType>
                         <Content><![CDATA[公交]]></Content>
                         <MsgId>1234567890123456</MsgId>
                        </xml>";
    		    break;
    		  
    		case 'image':
                return "<xml>
                         <ToUserName><![CDATA[toUser]]></ToUserName>
                         <FromUserName><![CDATA[fromUser]]></FromUserName>
                         <CreateTime>1348831860</CreateTime>
                         <MsgType><![CDATA[image]]></MsgType>
                         <PicUrl><![CDATA[this is a url]]></PicUrl>
                         <MediaId><![CDATA[media_id]]></MediaId>
                         <MsgId>1234567890123456</MsgId>
                        </xml>";
                break;

            case 'subscribe':
                return "<xml>
                         <ToUserName><![CDATA[gh_ad51f6e7384d]]></ToUserName>
                         <FromUserName><![CDATA[FromUser]]></FromUserName>
                         <CreateTime>123456789</CreateTime>
                         <MsgType><![CDATA[event]]></MsgType>
                         <Event><![CDATA[subscribe]]></Event>
                        </xml>";
                break;

            case 'unsubscribe':
                return "<xml>
                         <ToUserName><![CDATA[toUser]]></ToUserName>
                         <FromUserName><![CDATA[FromUser]]></FromUserName>
                         <CreateTime>123456789</CreateTime>
                         <MsgType><![CDATA[event]]></MsgType>
                         <Event><![CDATA[unsubscribe]]></Event>
                        </xml>";
                break;

            case 'location':
                return "<xml>
                        <ToUserName><![CDATA[toUser]]></ToUserName>
                        <FromUserName><![CDATA[fromUser]]></FromUserName>
                        <CreateTime>123456789</CreateTime>
                        <MsgType><![CDATA[event]]></MsgType>
                        <Event><![CDATA[LOCATION]]></Event>
                        <Latitude>23.137466</Latitude>
                        <Longitude>113.352425</Longitude>
                        <Precision>119.385040</Precision>
                        </xml>";
                break;
            case 'click':
                return "<xml>
                        <ToUserName><![CDATA[toUser]]></ToUserName>
                        <FromUserName><![CDATA[FromUser]]></FromUserName>
                        <CreateTime>123456789</CreateTime>
                        <MsgType><![CDATA[event]]></MsgType>
                        <Event><![CDATA[CLICK]]></Event>
                        <EventKey><![CDATA[EVENTKEY]]></EventKey>
                        </xml>";
                break;

            default:
                return $GLOBALS["HTTP_RAW_POST_DATA"];
                break;
    	}
    }
    
}
?>